package com.example.demo.controller;

import com.example.demo.ai.DeepSeekService;
import com.example.demo.ai.model.SessionState;
import com.example.demo.ai.model.InterviewQA;
import com.example.demo.service.ResponseCacheService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 面试API控制器，提供RESTful接口用于面试会话管理
 */
@RestController
@RequestMapping("/api/interview")
public class InterviewApiController {
    private static final Logger logger = LoggerFactory.getLogger(InterviewApiController.class);
    
    private final ConcurrentHashMap<String, SessionState> sessions = new ConcurrentHashMap<>();
    private final ObjectMapper objectMapper;
    private final DeepSeekService deepSeekService;
    private final ResponseCacheService responseCacheService;

    @Autowired
    public InterviewApiController(ObjectMapper objectMapper, 
                                 DeepSeekService deepSeekService, 
                                 ResponseCacheService responseCacheService) {
        this.objectMapper = objectMapper;
        this.deepSeekService = deepSeekService;
        this.responseCacheService = responseCacheService;
    }

    /**
     * 开始面试
     */
    @PostMapping("/start")
    public ResponseEntity<Map<String, Object>> start(@RequestBody Map<String, Object> request) {
        try {
            String resumeText = (String) request.get("resumeText");
            String position = (String) request.get("position");
            
            if (resumeText == null || resumeText.isEmpty()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("error", "简历内容不能为空");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            String sessionId = generateSessionId();
            SessionState state = new SessionState(sessionId, resumeText, position);
            sessions.put(sessionId, state);
            
            // 生成第一个问题
            String firstQuestion = generateFirstQuestion(resumeText, position);
            state.addHistoryEntry("assistant", firstQuestion);
            state.incrementQuestionCount();
            
            Map<String, Object> response = new HashMap<>();
            response.put("sessionId", sessionId);
            response.put("welcomeMessage", "你好，欢迎参加面试");
            response.put("firstQuestion", firstQuestion);
            response.put("interviewActive", true);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("开始面试失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "开始面试失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 回答问题
     */
    @PostMapping("/{sessionId}/answer")
    public ResponseEntity<Map<String, Object>> answer(@PathVariable String sessionId, 
                                                     @RequestBody Map<String, Object> request) {
        try {
            SessionState state = sessions.get(sessionId);
            
            if (state == null) {
                return ResponseEntity.notFound().build();
            }
            
            if (!state.isActive()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("error", "面试已结束");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            String answer = (String) request.get("answer");
            if (answer == null || answer.isEmpty()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("error", "回答内容不能为空");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            // 记录用户回答
            state.addHistoryEntry("user", answer);
            
            // 先判断是否需要结束面试（已回答的问题数量 >= 最大问题数量）
            if (state.getQuestionCount() >= 10) {
                return endInterview(state);
            }
            
            // 生成下一个问题
            String nextQuestion = generateNextQuestion(state);
            state.addHistoryEntry("assistant", nextQuestion);
            state.incrementQuestionCount();
            
            Map<String, Object> response = new HashMap<>();
            response.put("nextQuestion", nextQuestion);
            response.put("interviewActive", true);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("处理回答失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "处理回答失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 生成会话ID
     */
    private String generateSessionId() {
        return UUID.randomUUID().toString();
    }

    /**
     * 生成第一个面试问题
     */
    private String generateFirstQuestion(String resumeText, String position) {
        try {
            // 使用DeepSeekService生成第一个问题
            // 这里使用generateSingleInterviewQuestion方法
            // 由于没有之前的问题，传递一个空列表
            List<String> previousQuestions = new ArrayList<>();
            return deepSeekService.generateSingleInterviewQuestion(
                    resumeText, 
                    position, 
                    "", // 空的职位描述
                    "", // 空的行业
                    2, // 默认中级难度
                    previousQuestions
            );
        } catch (Exception e) {
            logger.error("生成第一个问题失败，使用默认问题", e);
            // 如果生成失败，使用默认问题
            return "请简单介绍一下你自己。";
        }
    }

    /**
     * 生成下一个面试问题
     */
    private String generateNextQuestion(SessionState state) {
        try {
            // 从历史记录中提取问答对
            List<InterviewQA> qaList = new ArrayList<>();
            List<SessionState.HistoryEntry> history = state.getHistory();
            
            // 历史记录的格式是 assistant -> user -> assistant -> user...
            // 我们需要提取 assistant的问题和user的回答
            for (int i = 0; i < history.size() - 1; i += 2) {
                SessionState.HistoryEntry questionEntry = history.get(i);
                SessionState.HistoryEntry answerEntry = history.get(i + 1);
                
                if ("assistant".equals(questionEntry.getRole()) && "user".equals(answerEntry.getRole())) {
                    InterviewQA qa = new InterviewQA();
                    qa.setQuestion(questionEntry.getContent());
                    qa.setAnswer(answerEntry.getContent());
                    qaList.add(qa);
                }
            }
            
            // 使用DeepSeekService生成下一个问题，结合之前的问答
            return deepSeekService.generateSingleInterviewQuestionWithAnswers(
                    state.getResumeText(),
                    state.getPosition(),
                    "", // 空的职位描述
                    "", // 空的行业
                    2, // 默认中级难度
                    qaList
            );
        } catch (Exception e) {
            logger.error("生成下一个问题失败，使用默认问题", e);
            // 如果生成失败，使用默认问题
            return "你对我们公司有什么了解？";
        }
    }

    /**
     * 结束面试
     */
    private ResponseEntity<Map<String, Object>> endInterview(SessionState state) {
        try {
            state.setActive(false);
            
            // 从历史记录中提取问答对
            List<InterviewQA> qaList = new ArrayList<>();
            List<SessionState.HistoryEntry> history = state.getHistory();
            
            // 历史记录的格式是 assistant -> user -> assistant -> user...
            // 最后一个可能是assistant的问题，没有对应的回答
            for (int i = 0; i < history.size() - 1; i += 2) {
                SessionState.HistoryEntry questionEntry = history.get(i);
                SessionState.HistoryEntry answerEntry = history.get(i + 1);
                
                if ("assistant".equals(questionEntry.getRole()) && "user".equals(answerEntry.getRole())) {
                    InterviewQA qa = new InterviewQA();
                    qa.setQuestion(questionEntry.getContent());
                    qa.setAnswer(answerEntry.getContent());
                    qaList.add(qa);
                }
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("interviewActive", false);
            response.put("message", "面试已完成，感谢您的参与！");
            response.put("totalQuestions", state.getQuestionCount());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("结束面试失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "结束面试失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
}